package com.roc.web.action.settlemgr;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.MerinfoSearchBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.SettleWhilteList;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtInf;
import com.roc.service.IMerchantServices;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.SettleWhilteListService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/settleWhilteList")
public class SettleWhilteListAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(SettleWhilteListAction.class);
	
	private TblMchtInf tblMchtInf;
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	private SettleWhilteListSearchCondition searchCondition;
	
	@Autowired
	private IorgService orgService;
	@Autowired
	private IPageService pageService;
	@Autowired
	private IPowerInfoService ipowerInfoService;
	@Autowired
	private IMerchantServices merchantService;
	@Autowired
	private SettleWhilteListService settleWhilteListService;
	
	/**
	 * 页面初始化
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/settleWhilteList/merinfoList.jsp")
		,@Result(name = "error", location = "/error.jsp")
	})
	public String init() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		// 权限判断 查询录入权限（直营机构管理员，受理市场运营）
		if ((op.getRoleType().equals(Role.O_MANAGER.getCode()) && op.getGroupCd().equals("0")) //*** 上线时 1
				|| op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				org();
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
    }
	
	/**
	 * 查找商户信息
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryMerinfo", 
			results = { @Result(name = "success", location = "/pages/settleWhilteList/merinfoList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryMerinfo() throws Exception{
		try {
			Operators loginOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			// 1.权限判断
			if ((loginOperators.getRoleType().equals(Role.O_MANAGER.getCode()) && loginOperators.getGroupCd().equals("0"))
					|| loginOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					|| loginOperators.getRoleType().equals(Role.SYSTEM.getCode())) {
				// 查询商户信息
				if(searchCondition == null){
					searchCondition = (SettleWhilteListSearchCondition)getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettleWhilteListSearchCondition();
					}
				}
				init(); 
				Map<String, String> map = ipowerInfoService.queryRealIdByOpId(loginOperators.getSuperiorId(), loginOperators.getRoleType(), loginOperators.getId(), loginOperators.getOrgCode());
				String orgCode = map.get("orgCode");
				String superRole = map.get("superRole");
				String opRealId = map.get("opRealId");
				searchCondition.setGroupCd(map.get("groupCd"));
				searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
				searchCondition.setRoleId(superRole);// 角色
				searchCondition.setOpId(opRealId);//当前人员id
				searchCondition.setRoleId(loginOperators.getRoleType());//当前人员角色
				searchCondition.setOneOrgCode(loginOperators.getOneagentid());//机构
				
				Operators op = ipowerInfoService.queryYyAgentId(loginOperators.getId());
				
				int rows=pageService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				
				List<MerinfoSearchBean> msList=new ArrayList<MerinfoSearchBean>();
				StringBuffer sb = new StringBuffer();
				if(searchRsList.size()>0 && searchRsList!=null){
					Iterator iterator=searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj= (Object[])iterator.next();
						MerinfoSearchBean  msb=new MerinfoSearchBean(); 
						msb.setMid(Constance.Null2EmptyTrim(obj[0]));//商户号
						msb.setMerName(Constance.Null2EmptyTrim(obj[1]));//商户简称
						msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));//商户全称（全称）
						msb.setMerKind(Constance.Null2EmptyTrim(obj[3])); //所属机构、代理商
						msb.setPerName(Constance.Null2EmptyTrim(obj[4]));//业务联系人
						String phone=Constance.Null2EmptyTrim(obj[5]);//业务联系人手机号
						if(null != loginOperators.getAgentType() && !loginOperators.getAgentType().equals("1")){
							msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号  
						}else{
							msb.setPerPhone(phone);//手机号
						}
						msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));//法人
						String cardNo=Constance.Null2EmptyTrim(obj[7]);//法人证件号
						if(null != loginOperators.getAgentType() && !loginOperators.getAgentType().equals("1")){
							msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
						}else{
							msb.setCardNo(cardNo);//证件号
						}
						msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));// 营业执照号码
						msb.setAddr(Constance.Null2EmptyTrim(obj[9]));//详细地址
						msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
						msb.setAreaCode(Constance.Null2EmptyTrim(obj[11]));//
						msb.setAgentId(Constance.Null2EmptyTrim(obj[12]));//所属代理商
						msb.setRsvl(Constance.Null2EmptyTrim(obj[13]));//结算银行账户名称
						String account=Constance.Null2EmptyTrim(obj[14]);
						if(null != loginOperators.getAgentType() && !loginOperators.getAgentType().equals("1")){
							msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
						}else{
							msb.setRsvl3(account);//结算银行账户
						}
						
						msb.setAmount1(Constance.Null2EmptyTrim(obj[15]));//结算银行名称
						msb.setAmount2(Constance.Null2EmptyTrim(obj[16]));//联行号
						if(!Constance.Null2EmptyTrim(obj[17]).equals("0")){
							sb.append(Constance.Null2EmptyTrim(obj[17]));
						}
						if(!Constance.Null2EmptyTrim(obj[18]).equals("0")){
							sb.append(Constance.Null2EmptyTrim(obj[18]));
						}
						if(!Constance.Null2EmptyTrim(obj[17]).equals("0") && !Constance.Null2EmptyTrim(obj[18]).equals("0") ){
							sb.setLength(0);
							sb.append(Constance.Null2EmptyTrim(obj[17])).append("/"+Constance.Null2EmptyTrim(obj[18]));
						}
						msb.setCycleId(sb.toString());
						msb.setRecUpdOpr(Constance.Null2EmptyTrim(obj[19]));
						sb.setLength(0);
						msList.add(msb);
					}
				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				getRequest().setAttribute("opid", loginOperators.getId());
				setSearchToConditionSession(searchCondition);
				return SUCCESS;
			}
			addActionError("无权限访问！！！");
			return ERROR;
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return ERROR;
	}
	
	/**
	 * 添加商户结算白名单信息
	 * @return
	 * @throws Exception
	 */
	@Action(value = "insert", 
			results = {@Result(name = "success", location = "/pages/settleWhilteList/merinfoList.jsp"),
					@Result(name = "input", location = "/pages/settleWhilteList/merinfoList.jsp"),
					@Result(name = "error", location = "/error.jsp")
    })
	public String insert() {
		Operators operators = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			// 1.权限判断
			org();
			if ((operators.getRoleType().equals(Role.O_MANAGER.getCode()) && operators.getGroupCd().equals("0"))
					|| operators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					|| operators.getRoleType().equals(Role.SYSTEM.getCode())) {
				// 添加商户结算白名单
				if(tblMchtInf.getId() == null || tblMchtInf.getId().equals("")) {
					getRequest().setAttribute("msg", "白名单添加失败，请选择商户信息！");
					return INPUT;

				}
				
				TblMchtInf mchtInf = merchantService.queryMerchat(tblMchtInf.getId());
				
				SettleWhilteList settleWhilteList = new SettleWhilteList();
				settleWhilteList.setGmtCreate(new Date());
				settleWhilteList.setMchtCode(mchtInf.getId());
				settleWhilteList.setNameBusi(mchtInf.getNameBusi());
				settleWhilteList.setRec_upd_opr(new Long(operators.getId()).toString());
				
				settleWhilteListService.insert(settleWhilteList);
				
				getRequest().setAttribute("msg", "添加商户白名单成功！");
			}
		} catch (Exception e) {
			logger.error("添加商户白名单失败！", e);
			addActionError("添加商户白名单失败！");
			return ERROR;
		}
		
		logger.info("【"+operators.getId()+"】添加结算白名单成功");
		return SUCCESS;
	}
	
	/**
	 * 查找商户结算白名单列表
	 * @return
	 * @throws Exception
	 */
	@Action(value = "findSettleWhilteList", 
			results = { @Result(name = "success", location = "/pages/settleWhilteList/merinfoList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String findSettleWhilteList() throws Exception{

		return null;
	}
	
	public void org() throws Exception{
		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			getRequest().setAttribute("areaList", ConfigProperties.getGBProviceProperties());
			//初始化机构
			orgList = orgService.queryOrgList();
			getRequest().setAttribute("product", ConfigMerinfoUtil.getProductList());//开通产品信息
			getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getPosFunction(ConfigMerinfoUtil.ALL_FUNCTION, false));//开通产品信息
			getRequest().setAttribute("posType", ConfigProperties.getSysDB1("Terminal_Type",true));//终端类型
			getRequest().setAttribute("org", loginOperators.getOrgCode());//机构
		}catch (Exception e) {
			logger.error("商户信息查询初始化失败",e);
			throw new Exception("商户信息查询初始化失败");
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public SettleWhilteListSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(SettleWhilteListSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public TblMchtInf getTblMchtInf() {
		return tblMchtInf;
	}

	public void setTblMchtInf(TblMchtInf tblMchtInf) {
		this.tblMchtInf = tblMchtInf;
	}

}
